package com.demon.framework.boot.web.context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @see org.springframework.web.servlet.mvc.condition.RequestConditionHolder 也可获取 request的属性
 * request 上下文 工具类
 * Created by zyj on 2017/1/4.
 */
public class RequestContext {

    private static final ThreadLocal<HttpServletRequest> reqLocal = new InheritableThreadLocal<>();

    /**
     * 清除request线程变量。
     */
    public static void clearHttpReq() {
        reqLocal.remove();
    }

    /**
     * 获取当前请求的Request
     */
    public static HttpServletRequest getHttpServletRequest() {
        return reqLocal.get();
    }

    public static void setHttpServletRequest(HttpServletRequest request) {
        reqLocal.set(request);
    }

    /**
     * 获取当前Session
     */
    public static HttpSession getHttpSession() {
        return reqLocal.get().getSession();
    }

    /**
     * 获取当前Session
     */
    public static HttpSession getHttpSession(boolean create) {
        return reqLocal.get().getSession(create);
    }


    /**
     * 获取当前上下文的值
     * 先从 request中取
     * <p>
     * 如果创建了session，再从session中取
     */
    public static Object getAttribute(String key) {
        Object retVal = getHttpServletRequest().getAttribute(key);
        if (null == retVal) {
            HttpSession httpSession = getHttpSession(false);
            if (null != httpSession) {
                retVal = httpSession.getAttribute(key);
            }

        }
        return retVal;
    }

}
